import React, { useState, useCallback, useEffect } from 'react';
import { Picker } from 'antd-mobile';
import { Common } from 'UtilsCommon';
import { Icon } from 'Configs';
import Components from 'Components';
import { useGetDataSourceOptions } from 'UseHooks';
import Base from './base';
import * as styles from '../styles/view.scss';

const getOptions = (property, view, pageAxis, parentValue) => {
    parentValue = parentValue || property.parentValue;

    Base.setValueTextName(property);
    const { valueName, textName } = property;

    const list1 = [];
    const list2 = [];

    const { dataSource } = property;
    let value = null; let text = null;
    if (Common.isArray(dataSource)) {
        const [dataSource1, dataSource2] = dataSource;

        if (Common.isArray(dataSource1) && Common.isArray(dataSource2)) {
            dataSource1.forEach(d => {
                text = d[textName];
                value = d[valueName];
                list1.push({ value, label: text });
            });

            dataSource2.forEach(d => {
                text = d[textName];
                value = d[valueName];
                list2.push({ value, label: text });
            });
        }
    }

    return [list1, list2];
};

const valueChange = (property, view, pageAxis, value) => {
    Base.childPropertiesChanged(property, view, value);
    if (property.valueChange) property.valueChange(value, Base.getSelectData(property, value));

    if (property.selectDataToProperties) Base.setSelectDataToProperties(property, view, Base.getSelectData(property, value));

    if (property.valueChangeEventActionName) {
        if (!Common.isEquals(property.value2, value)) {
            pageAxis.invokeEventAction(property.valueChangeEventActionName, { property, view, pageAxis });
        }
        property.value2 = value;
    }
};

const exists = (columns, value) => {
    const [list1, list2] = columns;
    const [v1, v2] = value;
    const item = Common.arrayFirst(list1, (f) => Common.isEquals(f.value, v1, true));
    if (item === null) return false;

    const item2 = Common.arrayFirst(list2, (f) => Common.isEquals(f.value, v2, true));
    if (item2 === null) return false;
    return true;
};

const getText = (columns, joinChar, value) => {
    const [list1, list2] = columns;
    const [v1, v2] = value;
    const item = Common.arrayFirst(list1, (f) => Common.isEquals(f.value, v1, true));
    if (item === null) return '';

    const item2 = Common.arrayFirst(list2, (f) => Common.isEquals(f.value, v2, true));
    if (item2 === null) return '';
    return item.label + joinChar + item2.label;
};

export default (props) => {
    const { property, view, pageId, pageAxis } = Base.getProps(props);

    const [visible, setVisible] = useState(false);
    const [value, setValue] = useState(Base.getInitValue(property));
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);

    const [columns, setColumns] = useGetDataSourceOptions(property, view, pageAxis, getOptions);

    const onChange = useCallback((vs) => {
        property.isChanged = true;
        const v = vs.join(property.joinChar);
        setValue(v);
        setVisible(false);
        Base.bindDataValue(property, v);
    }, [property, setValue, setVisible]);

    const onCancel = useCallback(() => setVisible(false), [setVisible]);

    const onShow = useCallback(() => setVisible(!visible), [setVisible]);

    useEffect(() => {
        valueChange(property, view, pageAxis, value);
        if (property.valuePropertyName && !property.valueProperty) {
            property.valueProperty = pageAxis.getViewProperty(property, property.valuePropertyName);
        }
        if (property.valueProperty) {
            const t = value ? property.getText() : property.valueProperty.defaultValue || property.valueProperty.text;
            property.valueProperty.value = t;
            property.valueProperty.setValue && property.valueProperty.setValue(t);
        }
    }, [property, view, pageAxis, value]);

    let value2 = Common.isNullOrEmpty(value) ? [] : value.split(property.joinChar);

    property.isSelect = true;
    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setValue = (v) => setValue(v);
    property.getValue = () => value;
    property.setColumns = (c) => setColumns(c);
    property.refreshOptions = () => setColumns(getOptions(property, view, pageAxis));
    property.getText = () => getText(columns, property.joinChar, value2);

    if (!isVisible) return null;

    let extra = "请选择" + (property.isNullable === false ? "" : "(可选)");

    if (property.emptyLabel) extra = property.emptyLabel;

    const className = Base.getClassName(property, styles);

    const { style, label, labelStyle, isAddColon, defaultValue, isNullable, isRed } = property;

    const isRed2 = property.isRed2 || (isNullable === false && isRed);

    const label2 = property.isLabel === false ? '' : label;

    if (!exists(columns, value2)) value2 = [];

    const textStyle = { ...property.textStyle };
    const text = value2.length === 0 ? extra : getText(columns, property.joinChar, value2);
    if (value2.length === 0) textStyle.color = '#9AA3BB';

    const dv = defaultValue ? defaultValue.split(property.joinChar) : null;

    return (
        <React.Fragment>
            <div className={className} style={style}>
                {label2 && <div style={Base.setStyle(labelStyle)}>
                    {isRed2 ? <span style={{ color: 'red', position: 'relative', paddingRight: '0.125rem', top: '0.125rem' }}>*</span> : ''}
                    {label2}{isAddColon ? '：' : ''}
                </div>}
                <div style={Base.setStyle(textStyle)} className='buttonActive' onClick={onShow}>
                    {!property.properties && text}
                    {!property.properties && <Icon type='down' color={textStyle.color} fontSize={textStyle.fontSize} />}
                    {property.properties && Components.Base.renderProperties(property, pageId)}
                </div>
            </div>
            <Picker value={value2}
                onConfirm={onChange}
                onCancel={onCancel}
                columns={columns}
                title={label}
                visible={visible}
                defaultValue={dv}>
            </Picker>
        </React.Fragment>
    );
};